<template>
    <div>
        <div>
            <div class="flex">
                <div class="">
                    <el-button type="primary" icon="el-icon-plus" plain
                        @click="showCreate">新建可回收物</el-button>
                </div>
                <el-form :inline="true" class="demo-form-inline e-m-l-80 e-flex-1 text-right">
                    <el-form-item>
                        <el-checkbox v-model="isUseable">包含未启用</el-checkbox>
                    </el-form-item>
                    <el-form-item>
                        <el-input placeholder="关键词搜索" prefix-icon="el-icon-search" v-model="key" clearable
                            @clear="getList" @input="$throttle(getList(true), 3000)"></el-input>
                    </el-form-item>
                    <el-form-item class="e-m-r-0">
                        <el-button type="primary" @click="getList">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 列表显示 -->
            <el-table :data="tableData" :border="true">
                <el-table-column prop="name" label="可回收物">
                    <template slot-scope="scope">
                        <span>{{ scope.row.name }}</span>
                        <!-- <span>{{ scope.row.isweighing == true?'':'（件）' }}</span> -->
                    </template>
                </el-table-column>
                <el-table-column prop="typename" label="归属类型" v-if="typeId == 0">
                </el-table-column>
                <el-table-column prop="onsiteprice" label="上门回收价格">
                    <template slot-scope="scope">
                        <span>{{ scope.row.onsiteprice }}</span>
                        <!-- <span>{{ scope.row.isweighing == true?'元/KG':'元/件' }}</span> -->
                    </template>
                </el-table-column>
                <el-table-column prop="storeprice" label="站点回收价格">
                    <template slot-scope="scope">
                        <span>{{ scope.row.storeprice }}</span>
                        <!-- <span>{{ scope.row.isweighing == true?'元/KG':'元/件' }}</span> -->
                    </template>
                </el-table-column>
                <el-table-column prop="isweighing" label="计算单位">
                    <template slot-scope="scope">
                        <span>{{ scope.row.isweighing == true?'按重量（KG）':'按数量（件）' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="sort" label="排序">
                </el-table-column>
                <el-table-column prop="usestate" label="是否启用">
                    <template slot-scope="scope">
                        <!-- <span>{{ scope.row.isOpen }}</span> -->
                        <el-switch v-model="scope.row.isOpen" @change="changeState(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column width="200" label="操作">
                    <template slot-scope="scope">
                        <div>
                            <el-button type="text" size="small" @click="showEdit(scope.row)">编辑</el-button>
                            <el-button type="text" size="small" @click="del(scope.row.id)">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 新建编辑可回收物 -->
        <el-dialog :title="isEdit ? '编辑可回收物' : '新建可回收物'" :visible.sync="createDialogVisible" width="800px" :append-to-body="true">
            <el-form ref="ruleForm" :model="form" :rules="rules" label-width="130px" v-if="createDialogVisible">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="归属类型" v-if="typeId == 0">
                    <el-cascader class="custom-placeholder" ref="chooseType" :placeholder="form.typename" separator="-" @change="SelectType" filterable clearable :props="{
                            lazy: true,
                            checkStrictly: true,
                            lazyLoad: loadType,
                            label: 'name',
                            value: 'id',
                            emitPath: false
                        }" style="width: 100%;margin-right: 20px" v-model="form.typeid">
                    </el-cascader>
                </el-form-item>
                <!-- <el-form-item label="减碳量百分比" prop="carbon">
                    <el-input v-model="form.carbon"></el-input>
                </el-form-item> -->
                <el-form-item label="排序" prop="sort">
                    <el-input v-model="form.sort"></el-input>
                </el-form-item>
                <el-form-item label="上门价" prop="onsiteprice">
					<div class="flex" style="align-items: center;">
						<el-input
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="form.onsiteprice.price">
							<template slot="prepend">价格</template>
							<span slot="suffix" class="el-input__icon">元/{{ form.isweighing?'公斤':'件' }}</span>
						</el-input>
						<el-switch v-model="form.onsiteprice.edit" active-text="允许修改"></el-switch>
					</div>
                    <div class="flex e-m-b-15 e-m-t-15" style="align-items: center;" v-if="form.onsiteprice.edit">
                        <el-input
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="form.onsiteprice.minprice">
							<template slot="prepend">允许修改最低价格</template>
							<span slot="suffix" class="el-input__icon">元/{{ form.isweighing?'公斤':'件' }}</span>
						</el-input>
                    </div>
                    <div class="flex" style="align-items: center;" v-if="form.onsiteprice.edit">
                        <el-input
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="form.onsiteprice.highprice">
							<template slot="prepend">允许修改最高价格</template>
							<span slot="suffix" class="el-input__icon">元/{{ form.isweighing?'公斤':'件' }}</span>
						</el-input>
                    </div>
				</el-form-item>
                <el-form-item label="站点价" prop="storeprice">
					<div class="flex" style="align-items: center;">
						<el-input
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="form.storeprice.price">
							<template slot="prepend">价格</template>
							<span slot="suffix" class="el-input__icon">元/{{ form.isweighing?'公斤':'件' }}</span>
						</el-input>
						<el-switch v-model="form.storeprice.edit" active-text="允许修改"></el-switch>
					</div>
                    <div class="flex e-m-b-15 e-m-t-15" style="align-items: center;" v-if="form.storeprice.edit">
                        <el-input
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="form.storeprice.minprice">
							<template slot="prepend">允许修改最低价格</template>
							<span slot="suffix" class="el-input__icon">元/{{ form.isweighing?'公斤':'件' }}</span>
						</el-input>
                    </div>
                    <div class="flex" style="align-items: center;" v-if="form.storeprice.edit">
                        <el-input
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="form.storeprice.highprice">
							<template slot="prepend">允许修改最高价格</template>
							<span slot="suffix" class="el-input__icon">元/{{ form.isweighing?'公斤':'件' }}</span>
						</el-input>
                    </div>
				</el-form-item>
                <el-form-item label="预估出库价" prop="packPrice">
                    <el-input v-model="form.packprice">
                        <span slot="suffix" class="el-input__icon">元/{{ form.isweighing?'公斤':'件' }}</span>
                    </el-input>
                </el-form-item>
                <el-form-item label="计算方式" prop="estimatedweight">
                    <span v-if="isEdit">{{form.isweighing? '按重量(KG)计算':'按数量(件)计算'}}</span>

                    <el-radio-group v-else v-model="form.isweighing">
                        <el-radio :label="true">按重量(KG)计算</el-radio>
                        <el-radio :label="false">按数量(件)计算</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="按件估重 （选填）" prop="estimatedweight">
                    <el-input v-model="form.estimatedweight"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remarks">
                    <el-input v-model="form.remarks" type="textarea"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="createDialogVisible = false">取消</el-button>
                <el-button v-if="isEdit" type="primary" @click="edit">编辑</el-button>
                <el-button v-else type="primary" @click="create">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    props:{
        typeId:{
            type: Number,
            default: 0
        }
    },
    data() {
        return {
            loading: false,
            tableData: [], //列表数据
            key: '', //搜索关键字
            isUseable: false,
            createDialogVisible: false, //新建弹窗显示
            isEdit: false,
            // 新建表单
            form: {
                "typeid":0,
                "id": 0,
                "name": "",
                "carbon": 1,
                "pic": "",
                "sort": null,
                "sellprice": null,
                "isweighing": true,
                "onsiteprice": {
                    "edit": true,
                    "price": null,
                    "minprice": null,
                    "highprice": null
                },
                "storeprice": {
                    "edit": true,
                    "price": null,
                    "minprice": null,
                    "highprice": null
                },
                "estimatedweight": null
            },
            rules: {
                name: [
                    { required: true, message: '请输入可回收物名称', trigger: 'blur' }
                ],
                sellprice: [
                    { required: true, message: '请输入预估出库价', trigger: 'blur' }
                ],
                onsiteprice: [
                    { required: true, message: '请输入上门价', trigger: 'blur' }
                ],
                storeprice: [
                    { required: true, message: '请输入站点价', trigger: 'blur' }
                ]
                // mobile: [
                //     { required: true, message: '请输入手机号', trigger: 'blur' },
                //     { pattern: /^1[3|4|5|7|8][0-9]\d{8}$/, message: '请输入正确的手机号', trigger: 'blur' }
                // ],
            },
        }
    },
    mounted() {
        this.getList()
    },
    watch: {
        createDialogVisible(val) {
            if (!val) {
                this.form = {
                    "typeid":0,
                    "id": 0,
                    "name": "",
                    "carbon": 1,
                    "pic": "",
                    "sort": null,
                    "sellprice": null,
                    "isweighing": true,
                    "onsiteprice": {
                        "edit": true,
                        "price": null,
                        "minprice": null,
                        "highprice": null
                    },
                    "storeprice": {
                        "edit": true,
                        "price": null,
                        "minprice": null,
                        "highprice": null
                    },
                    "estimatedweight": null
                }
                this.getList();
            }
        },
        isUseable(){
            this.getList(this.pid)
        }
    },
    methods: {
        // 返回上一页
        goBack() {
            this.$router.go(-1)
        },

        //加载可回收物
        loadType(node, resolve) {
            console.log('加载可回收物',node)
            const {
                level
            } = node;
            const pid = level === 0 ? 0 : node.value

            this.$axios.get(`Waste/Type/List?pid=${pid}`).then((datas) => {
                const nodes = datas
                    .filter(item => item.usestate === '已启用')
                    .map(c => ({
                        id: c.id,
                        name: c.name,
                        // leaf: c.hasChildren === false // 根据实际接口返回字段判断
                    }))
                resolve(nodes)
            }).catch(() => {
                resolve([]) // 清空加载状态
                this.$message.error('加载失败')
            })
        },
        // 选择分类
        SelectType(v){
            console.log('选择可回收物',v)
            this.form.typeid = v
        },

        // 获取数据
        getList() {
            this.$axios.get('Waste/product/List', {
                params:{
                    "typeid": this.typeId,
                    "key": this.key
                }
            }).then((res) => {
                let datas = res;
                datas.forEach(item => {
                    item.isOpen = item.usestate == '已启用' ? true : false;
                });
                this.tableData = datas;

                if(this.isUseable){
                    this.tableData = datas;
                }else{
                    this.tableData = datas.filter((item)=>item.usestate == '已启用');
                }
            }).finally(() => {
                this.loading = false;
            })
        },

        // 发起新建
        showCreate() {
            this.createDialogVisible = true;
            this.isEdit = false
            this.form.typeid = this.typeId
        },

        // 新建
        create() {
            this.$refs.ruleForm.validate(valid => {
                if (valid) {
                    // 创建一个去除空值的提交数据
                    const submitForm = this.removeEmptyFields(this.form);
                    this.$axios.post('/Waste/Product/Create', submitForm).then((res) => {
                        this.createDialogVisible = false
                        this.$message.success('提交成功');
                    })
                } else {
                    console.log('验证失败');
                }
            });
        },

        // 发起修改
        showEdit(obj) {
            console.log('发起修改',obj)
            this.createDialogVisible = true;
            this.isEdit = true
            this.form = {
                id: obj.id,
                typeid: obj.typeid,
                name: obj.name,
                typename: obj.typename,
                carbon: obj.carbon,
                isweighing: obj.isweighing,
                sort: obj.sort,
                packprice: obj.packprice,
                onsiteprice: {
                    edit: obj.editonsiteprice,
                    price: obj.onsiteprice,
                    minprice: obj.onsiteminprice,
                    highprice: obj.onsitehighprice
                },
                storeprice: {
                    edit: obj.editstoreprice,
                    price: obj.storeprice,
                    minprice: obj.storeminprice,
                    highprice: obj.storehighprice
                },
                estimatedweight: obj.estimatedweight,
                remarks: obj.remarks,
                usestate: obj.usestate
            }
            
        },

        // 修改可回收物
        edit() {
            this.$refs.ruleForm.validate(valid => {
                if (valid) {
                    // 创建一个去除空值的提交数据
                    const submitForm = this.removeEmptyFields(this.form);

                    this.$axios.post('/Waste/Product/Edit', submitForm).then((res) => {
                        this.createDialogVisible = false
                        this.$message.success('修改成功');
                    })
                } else {
                    console.log('验证失败');
                }
            });
        },

        // 去除空值字段的辅助函数
        removeEmptyFields(obj) {
            const formData = JSON.parse(JSON.stringify(obj)); // 深拷贝避免修改原对象
            
            // 递归处理对象中的空值
            const removeEmpty = (data) => {
                if (typeof data === 'object' && data !== null) {
                    if (Array.isArray(data)) {
                        return data.map(item => removeEmpty(item));
                    } else {
                        const result = {};
                        for (const key in data) {
                            if (Object.prototype.hasOwnProperty.call(data, key)) {
                                const value = data[key];
                                // 保留非空值的字段
                                if (value !== '' && value !== null && value !== undefined) {
                                    result[key] = removeEmpty(value);
                                }
                            }
                        }
                        return result;
                    }
                }
                return data;
            };
            
            return removeEmpty(formData);
        },

        // 删除可回收物
        del(id) {
            this.$confirm('此操作将永久删除该可回收物, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.get('/Waste/Product/Delete', {
                    params:{
                        id: id
                   }
                }).then((res) => {
                    this.$message.success('删除成功');
                    this.getList();
                })
            })
        },

        // 修改启用状态
        changeState(row) {
            console.log(row);
            if(row.isOpen){
                row.usestate = '已启用'
            }else{
                row.usestate = '已冻结'
            }

            this.$axios.post('/Waste/Product/SetState', {
                "ids": [row.id],
                "state": row.usestate
            }).then((res) => {
                this.$message.success('修改成功');
                this.getList();
            })
        }
    }
}
</script>

<style lang="scss" scoped>
    ::v-deep .custom-placeholder .el-input__inner::placeholder {
        color: #606266;
    }
    ::v-deep .custom-placeholder .el-input__inner::-webkit-input-placeholder { /* Chrome/Safari */
        color: #606266;
    }
    ::v-deep .custom-placeholder .el-input__inner::-moz-placeholder { /* Firefox */
        color: #606266;
    }
    ::v-deep .custom-placeholder .el-input__inner:-ms-input-placeholder { /* IE10+ */
        color: #606266;
    }
</style>